/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package researchgrants.parts.pi.departments;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import researchgrants.parts.db.Db;

/**
 *
 * @author DOStudent1
 */
public class School {

    public static School getBySchoolName(String schoolName) {
        return(new School(schoolName));
    }

    private String schoolName;

    private School(String schoolName) {
        this.schoolName=schoolName;
        syncDataFromDb();
    }

    private void syncDataFromDb() {
        try {
            Connection conn = Db.openDbConnection();
            PreparedStatement prepareStatement = Db.createPreparedStatement(conn, "SELECT SchoolName FROM tblSchools WHERE SchoolName=?");
            prepareStatement.setString(1, schoolName);
            ResultSet schoolResultSet = prepareStatement.executeQuery();
            Db.moveToFirstLine(schoolResultSet);

            schoolResultSet.close();
            prepareStatement.close();
            Db.closeDbConnection(conn);
        } catch (SQLException ex) {
            Logger.getLogger(School.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(School.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String getSchoolName() {
        return (schoolName);
    }
    
    public static List<School> getAllSchools() {
        List<School> schoolsList = null;
        try {
            schoolsList = new LinkedList<School>();
            Connection conn = Db.openDbConnection();
            PreparedStatement prepareStatement = Db.createPreparedStatement(conn, "SELECT SchoolName FROM tblSchools ORDER BY SchoolName");
            ResultSet schoolsResultSet = prepareStatement.executeQuery();

            while (schoolsResultSet.next()) {
                schoolsList.add(School.getBySchoolName((String) Db.getColumn(schoolsResultSet, 1)));
            }

            schoolsResultSet.close();
            prepareStatement.close();
            Db.closeDbConnection(conn);
        } catch (SQLException ex) {
            Logger.getLogger(School.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(School.class.getName()).log(Level.SEVERE, null, ex);
        }
        return schoolsList;
    }
    
}
